#pragma once
#include "stdafx.h"
#include "ASN.h"
#include "Form2.h"
#include "dgdef.h"
#include "aps.h"

using namespace aps;
using namespace efsod;

namespace RPO1 {

	using namespace System;
	using namespace System::ComponentModel;
	using namespace System::Collections;
	using namespace System::Windows::Forms;
	using namespace System::Data;
	using namespace System::Drawing;
	using namespace System::Text;
	using namespace System::Data::Odbc;
	using namespace System::IO;

	/// <summary>
	/// Summary for Form1
	///
	/// WARNING: If you change the name of this class, you will need to change the
	///          'Resource File Name' property for the managed resource compiler tool
	///          associated with all .resx files this class depends on.  Otherwise,
	///          the designers will not be able to interact properly with localized
	///          resources associated with this form.
	/// </summary>
	public ref class Form1 : public System::Windows::Forms::Form
	{
	public:
		Form1(void)
		{
			InitializeComponent();
		}

	protected:
		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		~Form1()
		{
			if (components)
			{
				delete components;
			}
		}
	private: System::Windows::Forms::ToolTip^  toolTip3;
	protected: 
	private: System::Windows::Forms::ToolTip^  toolTip2;
	private: System::Windows::Forms::Label^  label2;
	private: System::Windows::Forms::Label^  label1;
	private: System::Windows::Forms::CheckedListBox^  Passports;
	private: System::Windows::Forms::ColorDialog^  colorDialog1;
	private: System::Windows::Forms::RichTextBox^  richTextBox2;
	private: System::Windows::Forms::Button^  button2;
	private: System::Windows::Forms::Button^  button1;
	private: System::Windows::Forms::RichTextBox^  progress;

	private: System::ComponentModel::IContainer^  components;

	private:
		/// <summary>
		/// Required designer variable.
		/// </summary>


#pragma region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		void InitializeComponent(void)
		{
			this->components = (gcnew System::ComponentModel::Container());
			this->toolTip3 = (gcnew System::Windows::Forms::ToolTip(this->components));
			this->toolTip2 = (gcnew System::Windows::Forms::ToolTip(this->components));
			this->label2 = (gcnew System::Windows::Forms::Label());
			this->label1 = (gcnew System::Windows::Forms::Label());
			this->Passports = (gcnew System::Windows::Forms::CheckedListBox());
			this->colorDialog1 = (gcnew System::Windows::Forms::ColorDialog());
			this->richTextBox2 = (gcnew System::Windows::Forms::RichTextBox());
			this->button2 = (gcnew System::Windows::Forms::Button());
			this->button1 = (gcnew System::Windows::Forms::Button());
			this->progress = (gcnew System::Windows::Forms::RichTextBox());
			this->SuspendLayout();
			// 
			// toolTip2
			// 
			this->toolTip2->ShowAlways = true;
			// 
			// label2
			// 
			this->label2->AutoSize = true;
			this->label2->Location = System::Drawing::Point(14, 271);
			this->label2->Name = L"label2";
			this->label2->Size = System::Drawing::Size(48, 13);
			this->label2->TabIndex = 19;
			this->label2->Text = L"Progress";
			// 
			// label1
			// 
			this->label1->AutoSize = true;
			this->label1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 16, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->label1->Location = System::Drawing::Point(12, 21);
			this->label1->Name = L"label1";
			this->label1->Size = System::Drawing::Size(293, 26);
			this->label1->TabIndex = 18;
			this->label1->Text = L"Passport Signing Interface";
			// 
			// Passports
			// 
			this->Passports->CheckOnClick = true;
			this->Passports->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->Passports->FormattingEnabled = true;
			this->Passports->Location = System::Drawing::Point(16, 71);
			this->Passports->Name = L"Passports";
			this->Passports->Size = System::Drawing::Size(821, 184);
			this->Passports->TabIndex = 15;
			this->Passports->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::Passports_SelectedIndexChanged);
			// 
			// richTextBox2
			// 
			this->richTextBox2->BorderStyle = System::Windows::Forms::BorderStyle::FixedSingle;
			this->richTextBox2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->richTextBox2->Location = System::Drawing::Point(16, 50);
			this->richTextBox2->Name = L"richTextBox2";
			this->richTextBox2->Size = System::Drawing::Size(821, 22);
			this->richTextBox2->TabIndex = 17;
			this->richTextBox2->Text = L"        File No.      Passport No.           Holder Name";
			// 
			// button2
			// 
			this->button2->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->button2->Location = System::Drawing::Point(710, 287);
			this->button2->Name = L"button2";
			this->button2->Size = System::Drawing::Size(127, 27);
			this->button2->TabIndex = 16;
			this->button2->Text = L"Show Passports";
			this->button2->UseVisualStyleBackColor = true;
			this->button2->Click += gcnew System::EventHandler(this, &Form1::button2_Click);
			// 
			// button1
			// 
			this->button1->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->button1->Location = System::Drawing::Point(686, 363);
			this->button1->Name = L"button1";
			this->button1->Size = System::Drawing::Size(150, 27);
			this->button1->TabIndex = 14;
			this->button1->Text = L"Sign All Checked";
			this->button1->UseVisualStyleBackColor = true;
			this->button1->Click += gcnew System::EventHandler(this, &Form1::button1_Click);
			// 
			// progress
			// 
			this->progress->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Regular, System::Drawing::GraphicsUnit::Point, 
				static_cast<System::Byte>(0)));
			this->progress->Location = System::Drawing::Point(16, 287);
			this->progress->Name = L"progress";
			this->progress->Size = System::Drawing::Size(608, 103);
			this->progress->TabIndex = 13;
			this->progress->Text = L"";
			// 
			// Form1
			// 
			this->AutoScaleDimensions = System::Drawing::SizeF(6, 13);
			this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
			this->AutoScroll = true;
			this->ClientSize = System::Drawing::Size(852, 412);
			this->Controls->Add(this->label2);
			this->Controls->Add(this->label1);
			this->Controls->Add(this->Passports);
			this->Controls->Add(this->richTextBox2);
			this->Controls->Add(this->button2);
			this->Controls->Add(this->button1);
			this->Controls->Add(this->progress);
			this->Name = L"Form1";
			this->Text = L"Passport Signing Interface";
			this->Load += gcnew System::EventHandler(this, &Form1::Form1_Load);
			this->ResumeLayout(false);
			this->PerformLayout();

		}
#pragma endregion
	private: System::Void Form1_Load(System::Object^  sender, System::EventArgs^  e) {
				 toolTip2->SetToolTip(this->button2,"Click to view unsigned passports");
				 toolTip3->SetToolTip(this->button1,"Click to sign passports");
			 }

private: System::Void Passports_SelectedIndexChanged(System::Object^  sender, System::EventArgs^  e) {
			 System::String ^fileNo = Passports->SelectedItem->ToString();
			 System::String ^s = "\t";
			 int i = fileNo->IndexOf(s);
			 Form2 ^f2 = gcnew Form2(fileNo->Substring(0,i)->ToString());
			 f2->ShowDialog(this);
		 }

private: System::Void button2_Click(System::Object^  sender, System::EventArgs^  e) {
				 System::String ^str = "dsn=Passport Data;uid=siddhu;pwd=siddhu;";
				 System::Data::Odbc::OdbcConnection ^connection = gcnew System::Data::Odbc::OdbcConnection(str);
				 System::Data::Odbc::OdbcCommand ^command = connection->CreateCommand();
				 System::Data::Odbc::OdbcDataReader ^Reader;
				 command->CommandText = "SELECT file_number, passport_no, full_name FROM pdata WHERE passport_no <> 'NULL' and chip_serial_no IS NOT NULL and issuer_signature IS NULL";
				 connection->Open();
				 Reader = command->ExecuteReader();
				 System::String ^thisRow = "";
				 Passports->Items->Clear();
				 while(Reader->Read())
				 {
					thisRow = "";
					thisRow = System::String::Concat(Reader->GetValue(0)->ToString(),"\t", Reader->GetValue(1)->ToString(), "\t", Reader->GetValue(2)->ToString() + "\t");
					Passports->Items->Add(thisRow, true);
				 }
				 connection->Close();
				  toolTip2->SetToolTip(this->button2,"Click to view unsigned passports");
		 }

private: System::Void button1_Click(System::Object^  sender, System::EventArgs^  e) {
			System::String ^l;
			System::Collections::IEnumerator ^myenum = this->Passports->CheckedItems->GetEnumerator();
			System::String ^s;
			System::String ^p;
			System::String ^d = "\t";
			int t;
			//2. Create Data to sign and send to smart card signer for computing the signature
			//3. update signature and personalization timestamp
			//NOTE: It wont write to the passport ever as thats a time consuming process
			char *fileno = (char*)malloc(20);
			array<wchar_t, 1> ^c;
			BYTE d1[100];
			BYTE d2[70000];
			BYTE d11[500];
			BYTE d12[200];
			BYTE d13[500];
			BYTE ldsSO[1000];
			BYTE dataToSign[100];
			BYTE sod[5000];
			int ldsSOLength = sizeof(ldsSO);
			int dataToSignLen = sizeof(dataToSign);
			int sodLength = sizeof(sod);
			int j = 0;

			BYTE signature[128] = {0x98,0x0B,0xA6,0xC7,0xC1,0xAE,0x81,0xFE,0xD2,0xB9,0x5B,0xB6,0x43,0xC4,0xD2,0x88,0x59,0xEE,0x54,0x23,0x75,0x72,0x28,0x52,0xCF,0x4C,0x82,0x42,0xB2,0x41,0x80,0xFE,0x11,0xBA,0xDC,0x5B,0x4E,0xD4,0x09,0x3A,0x20,0xC6,0xF7,0xBD,0xFF,0xC4,0x0C,0xD0,0xDB,0x43,0xF9,0xAA,0x96,0x8A,0xE7,0x12,0x37,0x9F,0x76,0x2F,0xD1,0x55,0x62,0xC6,0x07,0xDA,0xC0,0x2D,0x0A,0xE0,0x4A,0xA7,0xC9,0xAE,0x7D,0xC1,0x01,0xD8,0x33,0x6F,0xA8,0xB9,0x72,0xFE,0x1B,0x2A,0xD4,0x63,0x74,0x2E,0x26,0xA5,0x3B,0xC4,0x44,0x20,0xCB,0xE4,0xFD,0x06,0xAC,0x83,0x06,0xD2,0x20,0x38,0xB9,0x40,0xDA,0x65,0xBA,0x30,0x5D,0xCE,0xD1,0x47,0x09,0x99,0x63,0xDF,0x3C,0x08,0x3D,0xFA,0x35,0x9E,0x1E,0x78};
			int m = 128;

			while(myenum->MoveNext()) {
				s = myenum->Current->ToString();
				t = s->IndexOf(d);
				p = s->Substring (0, t);
				c = gcnew array<wchar_t, 1>(p->Length);
				c->Initialize();
				c = p->ToCharArray();
				for(int i=0;i<p->Length;i++) fileno[i] = c[i];
				fileno[p->Length] = '\0';
				System::String ^str = "dsn=Passport Data;uid=siddhu;pwd=siddhu;";
				System::Data::Odbc::OdbcConnection ^connection = gcnew System::Data::Odbc::OdbcConnection(str);
				System::Data::Odbc::OdbcCommand ^command = connection->CreateCommand();
				System::Data::Odbc::OdbcDataReader ^Reader;
				command->CommandText = "SELECT * FROM pdata WHERE file_number ='" + p + "'";
				connection->Open();
				Reader = command->ExecuteReader();
				Reader->Read();
				int FileSize = 65*1024;
				array<System::Byte, 1> ^rawData = gcnew array<System::Byte, 1>(FileSize);
				rawData->Initialize();
				System::String ^pnum = Reader->GetValue(Reader->GetOrdinal("passport_no"))->ToString();
				System::IO::FileStream ^fs = gcnew System::IO::FileStream("FaceImage.jpg", System::IO::FileMode::OpenOrCreate, System::IO::FileAccess::Write);
				int towrite = Reader->GetBytes(Reader->GetOrdinal("portrait_image"), 0, rawData, 0, FileSize);
				fs->Write(rawData, 0, towrite);
				fs->Close();
				connection->Close();
				
				this->progress->AppendText("Processing started for passport number " + pnum + "\r");
				try {
				int len1 = aps::createDG1(fileno, d1, 100);
				this->progress->AppendText("DG1 created\r" );
				ofstream fout1("DG1.bin", ios::binary);
				fout1.write((char*)d1, len1);
				fout1.close();

				int len2 = aps::createDG2(fileno, d2, 70000);
				this->progress->AppendText("DG2 created\r");
				ofstream fout2("DG2.bin", ios::binary);
				fout2.write((char*)d2, len2);
				fout2.close();

				int len12 = aps::createDG12(fileno, "doc_signer.der", d12, 200);
				this->progress->AppendText("DG12 created\r");
				ofstream fout12("DG12.bin", ios::binary);
				fout12.write((char*)d12, len12);
				
				int len13 = aps::createDG13(fileno, d13, 500);
				this->progress->AppendText("DG13 created\r");
				ofstream fout13("DG13.bin", ios::binary);
				fout13.write((char*)d13, len13);
				
				int len11 = aps::createDG11(fileno, d11, 500);
				this->progress->AppendText("DG11 created\r");
				ofstream fout11("DG11.bin", ios::binary);
				fout11.write((char*)d11, len11);
				
				DG dgs[5] = {{1, len1, d1}, {2, len2, d2}, {11, len11, d11}, {12, len12, d12}, {13, len13, d13}};
				j = efsod::createLDSSecurityObject(dgs, 5, "sha-1", ldsSO, &ldsSOLength, "sha-1", dataToSign, &dataToSignLen);
				if (j != EFSOD_SUCCESS) this->progress->AppendText("Error in creating LDS\r");
				ofstream ldsf("LDS.bin", ios::binary);
				ldsf.write((char*)ldsSO, ldsSOLength);

				ofstream data("dataToSign.bin", ios::binary);
				data.write((char*)dataToSign, dataToSignLen);
				}
				catch (System::Exception ^excp) {
					this->progress->AppendText("Kindly execute again\r");
				}
				//connect to smart card
				//send data to sign to smart card and get the signature
				//signature to be updated in database
				command->CommandText = "UPDATE pdata set issuer_signature = '1' where file_number = '" + p + "'";
				connection->Open();
				Reader = command->ExecuteReader();
				Reader->Read();
				connection->Close();

				this->progress->AppendText("Processing done for passport number " + pnum + "\r");
			}

			toolTip3->SetToolTip(this->button1,"Click to sign passports");
		 }
	};
}
